package com.wholesale.commons;

import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.TextView;

public class NetConnectionUtil {

	/**
	 * 判断网络是否可用
	 * @param mActivity
	 * @return boolean true 可用， false 不可用
	 */
	public static boolean isNetworkAvailable(Activity mActivity) {
		Context context = mActivity.getApplicationContext();
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * 获取网络连接
	 * 
	 * @param url
	 * @return
	 */
	public static HttpURLConnection getURLConnection(final Activity mActivity,
			String url) {
		if (isNetworkAvailable(mActivity)) {
			String proxyHost = android.net.Proxy.getDefaultHost();
			java.net.Proxy proxy = null;
			if (proxyHost != null) {
				proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP,
						new InetSocketAddress(android.net.Proxy
								.getDefaultHost(), android.net.Proxy
								.getDefaultPort()));
			}
			try {
				if (proxy != null) {
					return (HttpURLConnection) new URL(url)
							.openConnection(proxy);
				} else {
					return (HttpURLConnection) new URL(url).openConnection();
				}
			} catch (Exception e) {
			}
		}
		AlertDialog.Builder builders = new AlertDialog.Builder(mActivity);
	      builders.setTitle("抱歉,暂时无法处理您的请求");
	      TextView convertView = new TextView(mActivity);
	      convertView.setText("网络异常，连接失败!");
	      convertView.setTextSize((float) 16.0);
	      builders.setView(convertView);
	      builders.setPositiveButton("确定",  new DialogInterface.OnClickListener(){
	        public void onClick(DialogInterface dialog, int which)
	        {
	          mActivity.finish();
	        }       
	      });
	      builders.show();
		return null;
	}
}
